﻿using UnityEngine.UIElements;

namespace winS.UnityEditor.UIElement
{
    /// <summary>
    /// Represents <see cref="UndoableValueControl{T}"/> with <see cref="Label"/>.
    /// </summary>
    public abstract class EditorField<T> : UndoableValueControl<T>, IEditorField
    {
        public Label label => GetLabel();

        /// <summary>
        /// 此字段正在作为其它元素的子字段使用.
        /// </summary>
        protected internal bool asSubField { get; private set; }

        private Label _label;

        internal EditorField(ElementFactory elementFactory) : base(elementFactory)
        {
            style.flexDirection = FlexDirection.Row;
            style.minHeight = EditorElementUtility.fieldMinHeight;
        }

        public Label GetLabel()
        {
            if (_label == null)
            {
                _label = EditorElementUtility.elementFactory.CreateLabel();
                if (!asSubField && elementFactory.currentLabelWidth.value > 0f) _label.style.width = elementFactory.currentLabelWidth;
                _label.style.marginRight = elementFactory.labelMarginRight;
                Insert(0, _label);
            }
            return _label;
        }

        void IEditorField.ApplySubFieldStyle()
        {
            if (asSubField) return;
            asSubField = true;
            style.minHeight = StyleKeyword.Auto;
            style.flexGrow = 1f;
            style.SetMargin(0f);
            if (_label != null) _label.style.width = StyleKeyword.Auto;
        }
    }
}